#!/bin/bash -l
#====================================================================================================
#                                       部署脚本
#====================================================================================================

[[ $# -lt 2 ]] &&{
  echo "命令使用方式："
    echo "sh $0 {服务名称} {k8s项目名称} [编译组件名称] [服务相对路径名] [k8s负载组件名称]"
  echo -e "\t服务名称: 应用服务名称，例如：think-app"
  echo -e "\tk8s项目名称: 应用部署在k8s环境中所属的项目名称，如：think-project"
  echo -e "\t编译组件名称: 选填，主要解决当服务名，和maven编译的组件名称不一致时需要填组件名称，当需要填'服务相对路径名'时，如果服务名称和maven编译的组件名称一致，该值可需要和'服务名称'一致"
  echo -e "\tk8s负载组件名称: 选填，主要解决服务组件经过灰度之后，导致负载组件名字变更，服务发布失败问题"
  exit 0
}
# 组件名称
project_name=${1}
# k8s项目名称
k8s_project_name=${2}
#服务相对路径名
project_relative_path="./"
workspace=$(pwd)

component_name=${1}
if [ -n "${3}" ];then
    component_name="${3}"
fi

if [ -n "${4}" ];then
    project_relative_path="${4}/"
fi

# 下载项目依赖
cd ${component_name}
export GO111MODULE=on
export GOPROXY=https://goproxy.cn
go mod tidy
go mod download
# 编译组件
go build -o ${component_name} main.go

# 生成构建镜像的目录
rm -rf ${workspace}/k8s/release
mkdir -p ${workspace}/k8s/release

cp -f ${workspace}/${project_relative_path}${component_name}/${component_name} ${workspace}/k8s/release/${component_name}
cp -f ${workspace}/${project_relative_path}${component_name}/Dockerfile ${workspace}/k8s/release/Dockerfile
cp -f ${workspace}/${project_relative_path}${component_name}/.env ${workspace}/k8s/release/.env
#====================================================================================================#
#                           镜像生成、推送部分，请勿修改                                                  #
#====================================================================================================#
cd ${workspace}/k8s/release
#声明基础镜像名称
from_image_name="192\.168\.153\.139\:30002\/library\/alpine\:latest"
sed -i "s/{FromBaseDockerImage}/${from_image_name}/g" ${workspace}/k8s/release/Dockerfile

image_tags=$(date +%s).${RANDOM}
#注意一定要加上项目名称，否则将镜像推送至harbor将失败
docker_image_name=192.168.153.139:30002/${k8s_project_name}/${component_name}:${image_tags}

docker build --build-arg PRG_NAME=${component_name} \
             -t ${docker_image_name} -f ${workspace}/k8s/release/Dockerfile .
docker login -u admin -p Harbor12345 192.168.153.139:30002
docker push ${docker_image_name}
deployment_name=${project_name}
if [ -n "${5}" ];then
    deployment_name="${5}"
fi
kubectl patch deployment ${deployment_name} -n ${k8s_project_name} --patch '{"spec": {"template": {"spec": {"containers": [{"name": "'${project_name}'","image":"'${docker_image_name}'"}]}}}}'